package com.suixun.service.credits.impl;

import java.util.Date;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.suixun.dao.CompanyAuditRecordMapper;
import com.suixun.dao.CompanyMapper;
import com.suixun.dao.credits.CompanyDao;
import com.suixun.entity.credits.Company;
import com.suixun.entity.credits.CompanyAuditRecord;
import com.suixun.entity.credits.CompanyExample;
import com.suixun.entity.credits.CompanyUser;
import com.suixun.entity.ext.credits.company.CompanyPage;
import com.suixun.entity.form.credits.company.CompanyForm;
import com.suixun.entity.form.credits.company.CompanyPageForm;
import com.suixun.service.credits.CompanyService;
import com.suixun.service.credits.CompanyUserService;
import com.suixun.vo.credits.BaseVo;
import com.suixun.vo.credits.ResponseVo;

/**
 * 商家相关资料
 * 
 * @author yh
 * @date 2017年12月7日
 */
@Service
public class CompanyServiceImpl implements CompanyService {

    @Autowired
    private CompanyMapper companyMapper;

    @Autowired
    private CompanyDao companyDao;

    @Autowired
    private CompanyUserService companyUserService;

    @Autowired
    private CompanyAuditRecordMapper auditRecordMapper;

    @Override
    public ResponseVo<CompanyPage> findPage(CompanyPageForm param) {
        Integer total = companyDao.findPageTatal(param);
        List<CompanyPage> list = null;
        if (total > 0) {
            list = companyDao.findPage(param);
        }
        return new ResponseVo<>(list, total);
    }

    @Override
    @Transactional
    public void insert(CompanyForm param, Integer userid) throws Exception {
        // 添加账号
        CompanyUser user = createCompanyUser(param);
        companyUserService.insert(user);
        // 添加商户
        Company company = createCompany(param);
        company.setCompanyUserId(user.getId());
        companyMapper.insertSelective(company);
        // 添加审核记录
        auditRecordMapper.insertSelective(createAuditRecord(company, userid));
    }

    @Override
    @Transactional
    public void update(CompanyForm param) throws Exception {

        Integer companyid = param.getId();
        String account = param.getAccount();

        // 修改账号
        if (StringUtils.isNotBlank(account)) {
            CompanyUser user = companyUserService.findByCompanyid(companyid);
            user.setAccount(account);
            companyUserService.update(user);
        }

        // 修改商户
        Company company = companyMapper.selectByPrimaryKey(companyid);
        if(company == null){
            throw new NullPointerException("商户不存在！");
        }
        Company updateCompany = new Company();
        BeanUtils.copyProperties(updateCompany, param);
        companyMapper.updateByPrimaryKeySelective(updateCompany);

    }

    @Override
    public CompanyForm findOneByCompanyid(Integer companyid) {
        return companyDao.findOneByCompanyid(companyid);
    }

    @Override
    @Transactional
    public void auditCompany(Integer companyid, String opinion, Boolean isPass, Integer userid) throws Exception {
        Company company = companyMapper.selectByPrimaryKey(companyid);
        if (company != null) {

            if (isPass) {
                company.setAuditState((short) 2);
            } else {
                company.setAuditState((short) 3);
            }
            companyMapper.updateByPrimaryKey(company);

            CompanyAuditRecord car = createAuditRecord(company, userid);
            car.setNote(opinion);
            auditRecordMapper.insertSelective(car);
        }
    }

    @Override
    public List<String> findAllName() {
        CompanyExample companyExample = new CompanyExample();
        companyExample.createCriteria();
        List<Company> list = companyMapper.selectByExample(companyExample);
        List<String> voList = null;
        if (!CollectionUtils.isEmpty(list)) {
            voList = Lists.transform(list, new Function<Company, String>() {
                @Override
                public String apply(Company pojo) {
                    return pojo.getName();
                }
            });
        }
        return voList;
    }

    @Override
    public boolean verifyName(String name, Integer companyid) {
        CompanyExample companyExample = new CompanyExample();
        companyExample.createCriteria().andNameEqualTo(name);
        List<Company> list = companyMapper.selectByExample(companyExample);
        if (CollectionUtils.isEmpty(list)) {
            return true;
        }
        Company company = list.get(0);
        // 修改时的校验
        if (companyid != null && companyid > 1) {
            Company sourceCompany = companyMapper.selectByPrimaryKey(companyid);
            if (sourceCompany == null) {
                return false;
            }
            if (company.getId().equals(sourceCompany.getId())) {
                return true;
            }
        }
        return false;
    }

    private Company createCompany(CompanyForm param) throws Exception {
        Company company = new Company();
        BeanUtils.copyProperties(company, param);
        company.setId(null);
        company.setType((short) 1);
        company.setAuditState((short) 2);
        company.setCreateTime(new Date());
        return company;
    }

    private CompanyUser createCompanyUser(CompanyForm param) {
        CompanyUser user = new CompanyUser();
        user.setName(param.getAccount());
        user.setAccount(param.getAccount());
        user.setPwd(param.getAccount());
        return user;
    }

    private CompanyAuditRecord createAuditRecord(Company company, Integer userid) throws Exception {
        CompanyAuditRecord car = new CompanyAuditRecord();
        BeanUtils.copyProperties(car, company);
        car.setId(null);
        car.setCompanyId(company.getId());
        car.setAuthUserId(userid);
        car.setCreateTime(new Date());
        car.setNote("此商户为运营后台创建");
        car.setBusinessName(company.getBusinessType());
        return car;
    }

    @Override
    public List<BaseVo> findAllPassName() {
        CompanyExample companyExample = new CompanyExample();
        companyExample.createCriteria().andAuditStateEqualTo((short) 2);
        List<Company> list = companyMapper.selectByExample(companyExample);
        List<BaseVo> voList = null;
        if (!CollectionUtils.isEmpty(list)) {
            voList = Lists.transform(list, new Function<Company, BaseVo>() {
                @Override
                public BaseVo apply(Company pojo) {
                    return new BaseVo(pojo.getId(), pojo.getName());
                }
            });
        }
        return voList;
    }
    
    @Override
    public void updateTop(Integer id, boolean isCancel) {
        if(id == null){
            throw new NullPointerException();
        }
        if(!isCancel){
            Company company = new Company();
            company.setId(id);
            company.setTop(new Date());
            companyMapper.updateByPrimaryKeySelective(company);
        }else{
            companyDao.cancelTop(id);
        }
    }

}
